import { computed, watch, reactive, ref } from 'vue'

export default function useWechatPicker(initialOptions, initialValue) {
  const options = reactive([])
  const value = ref(null)
  const index = ref(null)
  const text = computed(() => {
    return index.value != null
      ? options[index.value].text
      : value.value
  })

  watch(
    () => options,
    newOptions => {
      if (index.value != null) {
        const valueNewIndex = newOptions.findIndex(i => i.value === value.value)
        setIndex(Math.max(valueNewIndex, 0))
      } else {
        setIndex(0)
      }
    },
    { deep: true }
  )

  function setOptions(newOptions, config = {}) {
    const {
      textKey = 'text',
      valueKey = 'value',
      useAll = false,
    } = config

    const opts = newOptions.map(i => {
      return {
        text: i[textKey],
        value: i[valueKey],
      }
    })

    if (useAll) {
      opts.unshift({
        text: '全部',
        value: '',
      })
    }

    Object.assign(options, opts)
  }

  function setValue(newValue) {
    value.value = String(newValue)

    const idx = options.findIndex(i => i.value === value.value)
    index.value = idx !== -1 ? idx : null
  }

  function setIndex(newIndex) {
    index.value = Number(newIndex)

    value.value = options[index.value].value
  }

  if (initialOptions) {
    setOptions(initialOptions)
  }

  if (initialValue) {
    setValue(initialValue)
  }

  return reactive({
    options,
    index,
    value,
    text,
    setOptions,
    setValue,
    setIndex,
  })
}
